package com.stadium.web.service.impl;

import com.fastsite.common.api.ApiException;
import com.fastsite.common.domain.TokenUserObject;
import com.fastsite.common.enums.StatusEnum;
import com.fastsite.dao.utils.PageSort;
import com.fastsite.utils.DateUtils;
import com.fastsite.utils.StringUtils;
import com.stadium.web.domain.MarketActivity;
import com.stadium.web.domain.User;
import com.stadium.web.domain.Venue;
import com.stadium.web.service.MarketActivityService;
import com.stadium.web.service.UserService;
import com.stadium.web.service.VenueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import com.stadium.web.repository.ReserveRepository;
import com.stadium.web.domain.Reserve;
import com.stadium.web.service.ReserveService;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Formatter;
import java.util.List;

/**
 * 预定Service业务层处理
 * 
 * @author ruoyi
 * @date 2020-03-15
 */
@Service
public class ReserveServiceImpl implements ReserveService
{
    @Autowired
    private ReserveRepository reserveRepository;

    @Autowired
    private VenueService venueService;
    @Autowired
    private UserService userService;
    @Autowired
    private MarketActivityService marketActivityService;
    /**
     * 根据预定ID查询预定数据
     * @param id 预定ID
     */
    @Override
    @Transactional
    public Reserve getById(Long id) {
        return reserveRepository.findById(id).orElse(null);
    }

    /**
     * 获取分页列表数据
     * @param example 查询实例
     * @return 返回分页数据
     */
    @Override
    public Page<Reserve> getPageList(Example<Reserve> example) {
        // 创建分页对象
        PageRequest page = PageSort.pageRequest(null,Sort.Direction.ASC);
        return reserveRepository.findAll(example, page);
    }
    @Override
    @Transactional
    public Reserve reserveVenue(Reserve reserve, User user) {
        user = userService.getById(user.getId());
        Venue venue = venueService.getById(reserve.getVenueId());
        if(venue.getIsReserve()){
            throw new ApiException("该场馆已预定，请稍后重试");
        }
        //获取价格
        BigDecimal cost =venue.getCost();
        //获取优化力度
        List<MarketActivity> marketActivities = marketActivityService.findByVenueId(venue.getId());

        if(StringUtils.isNotNull(marketActivities)&&marketActivities.size()!=0){
            MarketActivity marketActivity = marketActivities.get(0);
            Date sysDate = DateUtils.getNowDate();
            Date fromTime =  marketActivity.getFromTime();
            Date toTime =  marketActivity.getToTime();
            if(sysDate.compareTo(fromTime)>=0&&sysDate.compareTo(toTime)<=0){
                Double discount  = marketActivity.getDiscount();
                cost.multiply(new BigDecimal(discount));
            }
        }
        BigDecimal balance =  user.getBalance();
        if(balance.compareTo(cost)<0){
            throw new ApiException("余额不足请充值");
        }
        balance.divide(cost);
        DecimalFormat df4 = new DecimalFormat();
        // #：位置上无数字不显示
        df4.applyPattern("0.##");
        balance = new BigDecimal( df4.format(balance));
        user.setBalance(balance);
        userService.save(user);
        return save(reserve);
    }

    //
    @Override
    @Transactional
    public Reserve save(Reserve reserve) {
        return reserveRepository.save(reserve);
    }



    /**
     * 状态(启用，冻结，删除)/批量状态处理
     */
    @Override
    @Transactional
    public Boolean updateStatus(StatusEnum statusEnum, List<Long> ids){
        // 删除预定时取消与预定和菜单的关联
        return reserveRepository.updateStatusByIdIn(statusEnum.getCode(), ids) > 0;
    }

    @Override
    public List<Reserve> getByUserId(Long userId) {
        return reserveRepository.findByUserId(userId);
    }

}
